package com.mgs.tagger.log
{
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;

	public class Logger
	{
		private static var _instance:Logger;
		
		public static function get instance():Logger{
			if(_instance == null){
				_instance = new Logger();
			}
			return _instance;
		}
		private var stream:FileStream;
		function Logger()
		{
			var logFile:File = File.applicationStorageDirectory.resolvePath("app.log");
			stream = new FileStream();
			stream.open(logFile, FileMode.APPEND);
			NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
		}
		private function onExit(event:Event):void{
			log(Level.INFO, "Application exit");
			if(stream != null){
				stream.close();
				stream = null;
			}
		}
		private function logMsg(message:String):void{
			trace(message);
			if(stream != null){
				stream.writeUTFBytes(message + "\n");
			}else{
				// open/close (log after exit)
				var logFile:File = File.applicationStorageDirectory.resolvePath("app.log");
				stream = new FileStream();
				stream.open(logFile, FileMode.APPEND);
				logMsg(message);
				stream.close();
				stream = null;
			}
		}
		public function log(level:Level, message:String, e:Error = null):void{
			if(e != null){
				message = message + " : " + e.message + " : " + e.getStackTrace();
			}
			logMsg(level.label + " " + message);
		}
	}
}